/**
 * 剑指 Offer 44. 数字序列中某一位的数字
 * https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/
 */

/**
 * @param {number} n
 * @return {number}
 */
function findNthDigit(n) {
  if (n < 10) {
    return n;
  }
  let preCount = 0;
  let count = 10;
  let power = 1;
  while (count < n + 1) {
    power += 1;
    const numCount = (10 ** power) - (10 ** (power - 1));
    preCount = count;
    count += (numCount * power);
  }
  const numIndex = Math.ceil((n + 1 - preCount) / power);
  const offset = (n + 1 - preCount) % power || power;
  const num = 10 ** (power - 1) + numIndex - 1;
  return String(num)[offset - 1];
}

console.log(findNthDigit(188));
console.log(findNthDigit(189));
console.log(findNthDigit(190));
console.log(findNthDigit(191));
console.log(findNthDigit(192));
